const BaseRest = require('./rest.js');

module.exports = class extends BaseRest {
  /**
   * 获取配置
   * @return {[type]} [description]
   */
  async getAction() {
    let data = {};
    if (this.id) {
      const row = await this.modelInstance.where({name: this.id}).find();
      
      data = JSON.parse(row.value);
      
      //think.logger.debug(data);
      return this.success(data);
    }
    
    // 页码
    const page = this.get('page') || 0;
    let map = {};
    if (this.get('group')) {
      map['group'] = this.get('group');
    }
    
    if (page > 0) {
      // 每页显示数量
      const pageSize = this.get('pageSize') || 10;
      
       //think.logger.debug(map);
      
      let list = await this.modelInstance.where(map).page(page, pageSize).order('id asc').countSelect();
      for (const i in list) {
        data[list[i].name] = JSON.parse(list[i].value);
      }
      return this.success(data);
    } else {
      // 不分页
      let list = await this.modelInstance.where(map).order('id asc').select();
      for (const i in list) {
        data[list[i].name] = JSON.parse(list[i].value);
      }
      return this.success(data);
    }
    
  }
  
  /**
   * 更新配置
   * @return {[type]} [description]
   */
  async putAction() {
    // const name = this.get('type');
    const name = this.id;
    
    const value = this.post();
    think.logger.debug(value);
    
    // 只允许更新value
    const item = await this.modelInstance.where({name: name}).find();
    // think.logger.debug(item);
    
    if (think.isEmpty(item)) {
      return this.fail(1000, '指定的配置项目不存在');
    } else {
      const res = await this.modelInstance.save(name, value);
      if (res) {
        await this.hook('configUpdate', {name: name, value: value});
        return this.success({id: res}, '更新成功');
      } else {
        return this.fail(1000, '更新失败');
      }
    }
  }
};
